package com.zua.controller;
import cn.hutool.http.HttpUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.zua.entity.CollectGoods;
import com.zua.entity.Good;
import com.zua.entity.Order;
import com.zua.entity.User;
import com.zua.service.GoodService;
import com.zua.service.OrderService;
import com.zua.service.UserService;
import com.zua.util.AlipayConfig;
import com.zua.util.JavaMailUtil;
import com.zua.util.JedisUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
@CrossOrigin(origins = "*",allowCredentials = "true")
@RestController
@RequestMapping("/User")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private GoodService goodService;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private OrderService orderService;
    /**
     * 分页查询所有用户
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/users")
    public Map showUser(@RequestParam(defaultValue = "1") Integer pageNum,
                        @RequestParam(defaultValue = "5")Integer pageSize){
        System.out.println("pageNum = " + pageNum);
        List<User> list = userService.showAll(pageNum, pageSize);
        PageInfo<User> pageInfo = new PageInfo<>(list, 10);
        long total = pageInfo.getTotal();
        int[] pages = pageInfo.getNavigatepageNums();
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("pages",pages);
        map.put("total",total);
        return map;
    }
    /**
     * 添加一个用户
     * @param user
     * @return
     */
    @PostMapping(value = "/users")
    public Map addOne(@RequestBody User user){
        System.err.println("user = " + user);
        HashMap<String, Object> map = new HashMap<>();
        try {
            userService.insertUser(user);
            map.put("status","success");
        } catch (Exception e) {
            map.put("status","failed");
            e.printStackTrace();
        }
        return map;
    }
    /**
     * 删除某个用户  伪删除  将用户状态转换为0
     * @param id
     * @return
     */
    @DeleteMapping(value = "/users/{id}")
    public Map remove(@PathVariable("id") Integer id){
        System.out.println("id = " + id);
        HashMap<String, Object> map = new HashMap<>();
        try {
            userService.deleteById(id);
            map.put("status","success");
        } catch (Exception e) {
            map.put("status","failed");
            e.printStackTrace();
        }
        return map;
    }
    /**
     * 修改对应的用户信息
     * @param user
     * @return
     */
    @PutMapping(value = "/users")
    public Map updateOne(@RequestBody User user){
        HashMap<String, Object> map = new HashMap<>();
        try {
            userService.updateUser(user);
            map.put("status","success");
        } catch (Exception e) {
            map.put("status","failed");
            e.printStackTrace();
        }
        return map;
    }
    /**
     * 登陆操作  查询账号密码  如果有 存入session  反之  返回failed
     * @param user
     * @return
     */
    @PutMapping("/user/login")
    public Map userLogin(@RequestBody User user){
        HashMap<String, Object> map = new HashMap<>();
        try {
            User user1 = userService.selectByName(user.getUsername());
            if(user.getPassword().equals(user1.getPassword())){
                HttpSession session = request.getSession();
                session.setAttribute("user",user1);
                map.put("status","success");
                map.put("user",user1);
            }else{
                map.put("status","failed");
            }
        } catch (Exception e) {
            map.put("status","failed");
            e.printStackTrace();
        }
        return map;
    }
    /**
     * 注册用户  同时将该用户存入session中 即表示也就登陆了
     * @param user
     * @return
     */
    @PostMapping("/user/register")
    public Map register(@RequestBody User user){
        HashMap<String, Object> map = new HashMap<>();
        try {
            userService.insertUser(user);
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            map.put("status","success");
            map.put("user",user);
        } catch (Exception e) {
            map.put("status","failed");
            e.printStackTrace();
        }
        return map;
    }
    /**
     * 第一次进入个人中心获取基本信息
     * @return
     */
    @GetMapping("/user/center")
    public Map center(){
        HashMap<String, Object> map = new HashMap<>();
        User user = (User) request.getSession().getAttribute("user");
        Integer num = goodService.selectNumById((int) user.getId());
        map.put("user",user);
        map.put("num",num);
        return map;
    }
    @GetMapping("/user/quit")
    public Map quit(){
        HashMap<String, Object> map = new HashMap<>();
        request.getSession().setAttribute("user",null);
        map.put("status","quit");
        return map;
    }
    /**
     * 搜索我的闲置
     * @return
     */
    @GetMapping("/user/selectGoods")
    public Map selectGoods(){
        HashMap<String, Object> map = new HashMap<>();
        User user = (User) request.getSession().getAttribute("user");
        List<Good> goods = goodService.selectByUserId((int) user.getId());
        for (Good good : goods) {
            good.setImgUrl("/ZuaMarket/good/upload/"+good.getImgUrl());
        }
        map.put("goods",goods);
        return map;
    }
    /**
     * 搜索我的收藏
     * @return
     */
    @GetMapping("/user/selectCollectGoods")
    public Map selectCollectGoods(){
        HashMap<String, Object> map = new HashMap<>();
        User user = (User) request.getSession().getAttribute("user");
        CollectGoods collectGoods = new CollectGoods();
        Jedis jedis = JedisUtils.getJedis();
        //card+userid 就是存入redis的键
        String key = "Cart"+user.getId();
        //获取对应用户的cart
        String cart = jedis.get(key);
        try {
            collectGoods = objectMapper.readValue(cart, CollectGoods.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取set集合  添加物品  set集合自动去重
        HashSet<Good> goods = collectGoods.getCollectSet();
        for (Good good : goods) {
            //同时  如果这个物品的状态是0  就去除
            if(goodService.selectById((int)good.getId()).getStatus()==0){
                goods.remove(good);
            }
        }
        collectGoods.setCollectSet(goods);
        try {
            String value = objectMapper.writeValueAsString(collectGoods);
            jedis.set(key,value);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        map.put("goods",goods);
        return map;
    }
    /**
     * 用户修改个人基本信息
     * @param user
     * @return
     */
    @PutMapping("/user/changeUser")
    public Map changeUser(@RequestBody User user){
        HashMap<String, Object> map = new HashMap<>();
        map.put("user",user);
        try {
            userService.updateUser(user);
            request.getSession().setAttribute("user",user);
            map.put("state","success");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state","failed");
        }
        return map;
    }
    /**
     * 用户获取所有订单
     * @return
     */
    @GetMapping("/user/getOrders")
    public Map getOrders(){
        HashMap<String, Object> map = new HashMap<>();
        User user = (User) request.getSession().getAttribute("user");
            List<Order> orders = orderService.selectByUserId((int) user.getId());
        map.put("orders",orders);
        return map;
    }
    /**
     * 用户完成支付  支付之后向商品拥有者发送一条邮件
     * @param out_trade_no
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @RequestMapping("/user/payOrder")
    public ModelAndView changeOrder(String out_trade_no, HttpServletResponse response) throws Exception {
        orderService.payOrder(Integer.parseInt(out_trade_no));
        Order order = orderService.selectById(Integer.parseInt(out_trade_no));
        String goodName = order.getGoodName();
        long goodId = order.getGoodId();
        Good good = goodService.selectById((int) goodId);
        long userId = good.getUserId();
        User user = userService.selectById((int) userId);
        String email = user.getEmail();
        String username = user.getUsername();
        String msg = "尊敬的用户"+username+"，您的商品"+goodName+"已售出，请联系管理员进行送货";
        JavaMailUtil.sendMail(email, msg);
        return new ModelAndView("redirect:/user/user.jsp");
    }
}
